package com.wonders.frame.chron.dao.catalog.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;


@Repository
public class CatalogDaoImpl{

	@PersistenceContext
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	public List<Integer> findSpecificTypeChildren(String pId, String pType, List<String> nTypes) {
		try {
			String sql = "select t.n_id from  "
					+ "(select a.* from af_relation a where a.removed = 0 and a.rule_type_id=1) t "
					+ "where t.n_type in :nType "
					+ "start with t.p_type = :pType and t.p_id = :pId connect by prior t.n_type=t.p_type and prior t.n_id=t.p_id";
			Query query = em.createNativeQuery(sql);
			query.setParameter("pId", pId).setParameter("pType", pType).setParameter("nType", nTypes);
			List<Integer> result = query.getResultList();
			return result;
		} catch (Exception e) {
			return null;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}
	@SuppressWarnings("unchecked")
	public String findByCardsOrSummarys(List<Integer> pIds, String pType,String nType) {

		String ids="";
		try {
			String sql = "select t.n_id from  "
					+ "(select a.* from af_relation a where a.removed = 0 and a.rule_type_id=1) t "
					+ "where t.n_type = :nType "
					+ "start with t.p_type = :pType and t.p_id in :pId connect by prior t.n_type=t.p_type and prior t.n_id=t.p_id";
			Query query = em.createNativeQuery(sql);
			query.setParameter("pId", pIds).setParameter("pType", pType).setParameter("nType", nType);
			List<Integer> result = query.getResultList();
			if (result.size()>0) {
				ids = StringUtils.join(result, ",");	
			}
			return ids;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (em != null) {
				em.close();
			}
		}
	}

}
